package main

import (
	"encoding/hex"
	"encoding/json"
	"errors"
	"github.com/gogf/gf/v2/crypto/gaes"
	"github.com/gogf/gf/v2/encoding/gjson"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/gclient"
	"github.com/gogf/gf/v2/os/gctx"
)

var (
	AesKey = []byte("202CB962AC59075B964B07152D234B70")
	AesIv  = []byte("233FA6B19FDE8CAF")
	//SignKey = "D9840773233FA6B19FDE8CAF765402F5"
)

func main() {
	var (
		ctx          = gctx.New()
		ghttp        = g.Client()
		params       = g.Map{}
		paramsJson   []byte
		paramsText   []byte
		gResponse    *gclient.Response
		responseJson []byte
		err          error
	)
	params["pagination"] = true
	if paramsJson, err = json.Marshal(params); err != nil {
		return
	}
	if paramsText, err = Encrypt(paramsJson); err != nil {
		return
	}
	if gResponse, err = ghttp.Post(ctx, "https://appapidev.yeebok.cn/food/activity/getList", paramsText); err != nil {
		return
	}
	defer gResponse.Close()

	if responseJson, err = Decrypt(gjson.New(gResponse.ReadAllString()).Get("resData").String()); err != nil {
		return
	}
	gResponse.RawDump()
	g.Dump(responseJson)

}

func Encrypt(plainText []byte) (bodyText []byte, err error) {
	var (
		BodyHex []byte
	)
	if BodyHex, err = gaes.EncryptCBC(plainText, AesKey, AesIv); err != nil {
		return
	}
	bodyText = HexEncode(string(BodyHex))
	return
}

// HexDecode 16进制解码
func HexDecode(s string) ([]byte, error) {
	dst := make([]byte, hex.DecodedLen(len(s))) //申请一个切片, 指明大小. 必须使用hex.DecodedLen
	n, err := hex.Decode(dst, []byte(s))        //进制转换, src->dst
	if err != nil {
		g.Dump(err)
		err = errors.New("解析失败")
		return nil, err
	}
	return dst[:n], err //返回0:n的数据.
}

// HexEncode 字符串转为16进制
func HexEncode(s string) []byte {
	dst := make([]byte, hex.EncodedLen(len(s))) //申请一个切片, 指明大小. 必须使用hex.EncodedLen
	n := hex.Encode(dst, []byte(s))             //字节流转化成16进制
	return dst[:n]
}

// Decrypt 解密
func Decrypt(cipherText string) (bodyText []byte, err error) {
	var (
		BodyHex []byte
	)
	// 解密
	if BodyHex, err = HexDecode(cipherText); err != nil {
		return
	}
	if bodyText, err = gaes.DecryptCBC(BodyHex, AesKey, AesIv); err != nil {
		return
	}
	return
}
